import { createRouter, createWebHistory } from 'vue-router'
import type { App } from 'vue'
import { cancelAllRequest } from '@/utils/request'
const routerHistory = createWebHistory()
// createWebHashHistory hash 路由
// createWebHistory history 路由
// createMemoryHistory 带缓存 history 路由
const Layout = () => import('@/layout/index.vue')
const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/home',
        component: () => import('views/home/index.vue')
      },
      {
        path: '/demo',
        name: 'demo',
        component: () => import('views/demo/index.vue')
      },
      {
        path: '/icon',
        name: 'icon',
        component: () => import('views/icon/index.vue')
      }
    ]
  }
]
const router = createRouter({
  history: routerHistory,
  routes: routes
})
router.beforeEach((to, from, next) => {
  cancelAllRequest()
  next()
})
// 删除/重置路由
export function resetRoute(): void {
  router.getRoutes().forEach((route) => {
    const { name } = route
    if (name) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
}

export function setupRouter(app: App<Element>) {
  app.use(router)
}
export default router
